# coding=utf-8

#~ class FakeOutput:
    #~ def __init__():
        #~ self.out = ''
    #~ def write =

def show_logs():
	if request.args(0) in 'delete clear'.split():
		session.logs = {}
	return dict( logs = session.logs )   

def show_session():
    return dict(session =  session)

def show_vars():
    return dict(request=request, response=response )


def db_auto_filename():
    return  "db_%s-%s.csv" % (request.application, request.now.strftime("%Y%m%d_%H%M%S"))

#~ @auth.requires( request.client=='127.0.0.1' or auth.has_membership( role='admin'))
def db_export():
    filename = db_auto_filename()
    #~ response.flash = 'Downloading file  "%s"' % filename
    #~ session.db_download_filename =  filename
    return A( 'Download file "%s"' % filename, _href=URL(r=request, f='db_download', args=[filename]) )

#~ def examples_invalidate_by_db_cache_keys():
    #~ for example in db(db.Cache_keys.id>0).select():
        #~ session.user

def invalidate_all_examples_caches():  # could be done with memcache flush...
    data__Examples=prefetch_db_table_to_dict('Examples')
    data__Topics=prefetch_db_table_to_dict('Topics')
    for id, example in data__Examples.items():
        #~ cache_invalidate_4example(id, force_get_key=True) # for batch ids
        key = cache_key_4example(id=id, force_get_key=True, data__Examples=data__Examples, data__Topics=data__Topics) # lets leave locale to be as in user_prefs
        session.cache_invalidate[key ]=True        
        
def examples_invalidated_cache_refresh_crawler():
    refreshes = []
    for key, invalidated in session.cache_invalidate.items():
        if invalidated:
            if key.startswith('example_view_4url'):
                try:
                    id = key.split('--')[1]
                    refreshes.append(
                        LI ( B(key), B(" state:%s, time:%s" % (invalidated, caching_time_get( key )) ), DIV( LOAD( c='default', f='example_view_4url.load' , args=[id], ajax=True ) ) )
                    ) 
                except Exception, e:
                    mylog( str(e) )
    return dict(refreshes_via_ajax=refreshes)
    
@auth.requires( (request.client=='127.0.0.1') or auth.has_membership( role='admin'))
def db_download():
    
    # from appadmin.py: csv()
    import gluon.contenttype
    response.headers['Content-Type'] = gluon.contenttype.contenttype('.csv')
    #~ filename = session.db_download_filename or db_auto_filename()
    filename = request.args(0) or db_auto_filename()
    response.headers['Content-disposition'] = 'attachment; filename=%s' % filename 
         
    #~ return str(db(query).select())

    #~ if request.args:
        #~ ofile_name = request.args[0]
    #~ else:
        #~ ofile_name = '/tmp/db.csv'
    #~ ofile = open(ofile_name, 'w')
    # from dal.py : __str__()
    ostream = s = cStringIO.StringIO()
    db.export_to_csv_file(ostream)
    
    return ostream.getvalue()

def add_root_topic():
    global root_id
    if db(db.Topics.id > 0).count() == 0:
        root_id = db.Topics.insert(name='root')
        #~ db.Topics[root_id].update_record(parent_id = root_id)
        db.Topics[root_id].update_record(parent_id = None)
        return root_id
    
admin_role = db(db.auth_group.role=='admin').select().first()
admin_group_id = admin_role.id if admin_role else db.auth_group.insert(role='admin')

@auth.requires( request.client=='127.0.0.1' or request.client=='localhost' or auth.has_membership( role='admin'))
def init_data():

    tables2init = request.args or "Languages Topics".split()
    
    if "Languages" in tables2init: 
        if db(db.Languages.id > 0).count() == 0:
            db.Languages.insert(name='Noname Language (change the name)', about="", extension='unknown', comment_till_line_end='#', comment_brackets=None )
            #~ db.Languages.insert(name='Any_other', extension='???')
    
    # WORKAROUND for Topics - to have initial root_id 
    # in case we don't have any topic at all (moved to tree_structures.py)

    if "Topics" in tables2init: 
        # we should know the root id in controller or other places, let's find it here
        # TODO: change it somehow -- root_id as default is good, but not necessary....
        add_root_topic()
        
    #~ else:
        #~ if not find_root_id():
            #~ raise Exception(T('Root topic not found'))
    response.flash = T("OK")
    return response.flash
                    
@auth.requires( request.client=='127.0.0.1' or request.client=='localhost' or auth.has_membership( role='admin'))
def init_auth():
# needed for importing

    # makes problems, when using db_import, as inserts groups prior to importing :/
    for table in 'Examples Topics'.split():
        role = table.lower()+"_editor"
        if db(db.auth_group.role==role).count() == 0:
            group_id = auth.add_group(role, 'Can edit (create/update/delete) "%s"' % table)
            auth.add_permission(group_id, 'create', table)
            auth.add_permission(group_id, 'update', table)
            auth.add_permission(group_id, 'delete', table)

        # should not insert more than one ??
        #~ if not admin_role:  # if we haven't had admin group earlier (and created it first time)
        if db(db.auth_permission.group_id==admin_group_id )( db.auth_permission.table_name==table).count()==0:  # if we haven't had admin group earlier (and created it first time)
            auth.add_permission(admin_group_id, 'create', table)
            auth.add_permission(admin_group_id, 'update', table)
            auth.add_permission(admin_group_id, 'delete', table)
        
            #~ for action in 'create update delete':
                #~ if not db(db.auth_permission.group_id==admin_group_id \
                            #~ & db.auth_permission.name == action \
                            #~ & db.auth_permission.table_name == table \
                         #~ ):
                        #~ auth.add_permission(admin_group_id, 'create', table)
    response.flash = T("OK")
    return response.flash

@auth.requires(auth.user_id==1 or request.client=='127.0.0.1')
def function_six():
    return 'you can read secret documents'


@auth.requires( (request.client=='127.0.0.1') or (request.client=='localhost') or auth.has_membership( role='admin'))
def db_import():
    # TODO: after import fix root.parent_id to be equal root.id
    form = FORM(str(T('import db from csv file'))+" ",
                INPUT(_type='file',_name='csvfile'),
                #~ INPUT(_type='hidden',_value=table,_name='table'),
                INPUT(_type='submit',_value='import'),
                )
                
    #~ csvfile_name = request.args(0) or '/tmp/db.csv'
    #~ csvfile = open(csvfile_name, 'r')
    if request.vars.csvfile != None:
        #~ try:
            result = db.import_from_csv_file(request.vars.csvfile.file)  # TODO: add option to not import users/auth stuff
            #~ import_csv(db[request.vars.table],
                       #~ request.vars.csvfile.file)
            response.flash = T('data uploaded')
        #~ except Exception, e:
            #~ response.flash = DIV(T('unable to parse csv file'),PRE(str(e)))

    return dict(form=form, csvfile=request.vars.csvfile)

#~ @auth.requires_membership( role='admin') 
@auth.requires( request.client=='127.0.0.1' or auth.has_membership( role='admin'))
def db_clear():
    #~ for table in 'Languages Topics Examples'.split():
    # except: auth_user auth_group auth_membership auth_permission auth_event
    tables = ' '.join( [
                 'Topics Languages  Examples' ,
                 'plugin_comments_comment plugin_rating_master plugin_rating_aux' ,
                 'Metadata CodeSurroundings QuestionsTests ExamplesKernel Examples_archive Topics_archive Topics_without_unique_and_parent Versioning',
                 'web2py_session_CodeByExample web2py_tickets_CodeByExample web2py_uploads_CodeByExample',
                 #'auth_user auth_group auth_membership auth_permission auth_event' # better don't clear auth
                ] )
    for table in tables.split():
        try:
            db(db[table].id>0).delete()
        except Exception, e:
            response.flash = DIV(response.flash, BR, T('Some problem'), PRE(str(e)))



#~ def reset_caches(): # deprecated in favour of caching_time_get way
    #~ cache_update_crawler(clear=True) # just call caches so keys would be ceared
    #~ # updating not implemented yet
    #~ cache_update_crawler()  # make new content
    

        
      
